<template>
    <a-card title="添加项目">
        <ProjectForm ref="formRef" v-model:value="formState"></ProjectForm>

        <div class="bottom-div">
            <a-space>
                <a-button @click="save" :loading="loading" size="large" type="primary">保存</a-button>
                <a-button @click="close" size="large">取消</a-button>
            </a-space>
        </div>
    </a-card>
</template>
<script setup lang="ts">
import { onActivated, ref } from 'vue'

import { useRouter } from "vue-router"
import { useTabStore } from '@/stores/tab'
import type { Project } from '@/types/Project'

import { postProject } from '@/api/projectApi'
import { message } from 'ant-design-vue'
import { useProjectStore } from '@/stores/project'
import ProjectForm from './projectForm.vue'
import { amapGeo } from '@/api/amapApi'
import dayjs from 'dayjs'

const projectStore = useProjectStore()
const tabStore = useTabStore()
const router = useRouter()
const formState = ref<Project>({})
const formRef = ref()
const loading = ref(false)

const save = async () => {
    loading.value = true



    try {
        await formRef.value.validate()

        let geo = await amapGeo(formState.value.cityName!)
        let location = geo.data.geocodes[0].location.split(",")
        formState.value.lng = location[0]
        formState.value.lat = location[1]
        let res = await postProject(formState.value)

        message.success('新增成功')
        projectStore.reloadList = true
        formState.value = {}
        formRef.value.resetFields()
        close()

    } catch (error) {

    }
    loading.value = false

}

const close = () => {
    router.back()
    tabStore.removeTab(router.currentRoute.value.fullPath)

}
onActivated(() => {


    formState.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')


})

</script>
<style scoped>
.bottom-div {
    padding: 30px 0;
    text-align: center;
}
</style>